package com.qingniao.hb.service.impl;

import com.qingniao.hb.dao.BookDao;
import com.qingniao.hb.dao.impl.BookDaoImpl;
import com.qingniao.hb.entity.Books;
import com.qingniao.hb.service.BookService;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xlzhang
 * @date 2023/4/18 10:57
 */
@Slf4j
public class BookServiceImpl implements BookService {
    /**
     * dao的功能都是原子性的
     */
    private final BookDao bookDao = new BookDaoImpl();

    /**
     * 分页数据的要求：
     * 应该返回一个分页数据的对象给我，可以将分页数据封装到map
     * 分页数据：bookList, currentPage, pages, total
     * @param paramsMap 动态条件参数
     * @return
     */
    @Override
    public Map<String, Object> findBooksByParams(HashMap<String, Object> paramsMap) {
        try {
            // 1. 根据条件查询当前分页的列表数据
            List<Books> booksList = bookDao.selectPageByParams(paramsMap);
            log.debug("bookList: {}",booksList);
            // 2. 查询符合条件的总数据条数
            Long total = bookDao.selectCountByParams(paramsMap);
            log.debug("total: {}",total);

            // 3. 根据总条数和当前每页要显示数据的条数来计算总的分页数
            final Integer limit = (Integer) paramsMap.get("limit");
            // 需要保证所有的小数位必须要 + 1
            int pages = (int)(Math.ceil(total*1.0 / limit));

            // 4. 将所有数据封装一个map返回
            final HashMap<String, Object> pageData = new HashMap<>();
            pageData.put("bookList",booksList);
            pageData.put("total",total);
            pageData.put("currentPage",paramsMap.get("page"));
            pageData.put("pages",pages);
            // 将当前的查询参数重新返回给浏览器，保持表单数据的持续显示
            pageData.put("searchData",paramsMap);

            return pageData;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean addBook(Books books) {
        try {
            return bookDao.insertBook(books) > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean updateBook(Books books) {
        try {
            return bookDao.updateBook(books) > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean delBook(String bid) {
        try {
            return bookDao.deleteBook(bid) > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteBatch(String[] bids) {
        try {
            return bookDao.deleteBatch(bids) > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}








